/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.SearchView;

import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class AddContactActivity extends BaseActivity {
    private static final int QUERY_FAILURE = 0;
    private static final int QUERY_SUCCESS_HAVE_NO_ONE = 1;
    private static final int QUERY_SUCCESS_GET_IT = 2;
    private static final String TAG = "AddContactActivity";
    private LinearLayout searchedUserLayout;
    private TextView nameText;

    private ImageView avatar;

    private ProgressDialog progressDialog;

    private EditText et_reason;

    private User targetUser;
    private CheckBox cb_location;
    private SearchView searchView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contact);
        searchedUserLayout = findViewById(R.id.ll_user);
        nameText = findViewById(R.id.tv_nick);
        avatar = findViewById(R.id.avatar);
        et_reason = findViewById(R.id.et_reason);
        cb_location = findViewById(R.id.cb_location);
        searchView = findViewById(R.id.search_view);
        searchView.setListener(new SearchView.InteractionListener() {
            @Override
            public void onSearch(String content) {
                if (TextUtils.isEmpty(content)) {
                    showToast_v1("请输入要查找的电话号码");
                    return;
                }

                if (!Utils.checkMobileNum(content)) {
                    showToast_v1("请输入11位电话号码");
                    return;
                }
                searchContact(content);
            }

            @Override
            public void onTextChange(String content) {

            }
        });

        if (getIntent().hasExtra(EaseConstant.EXTRA_TARGET_USER_INFO)) {
            targetUser = getIntent().getParcelableExtra(EaseConstant.EXTRA_TARGET_USER_INFO);
            showTargetUserInfo();
        }

    }


    /**
     * 绑定菜单
     */
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_find_contact, menu);
//        return true;
//    }


    /**
     * search contact
     *
     * @param
     */
    public void searchContact(String content) {
        hideSoftKeyboard();
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        if (searchedUserLayout.isShown()) {
            searchedUserLayout.setVisibility(View.INVISIBLE);
        }

        final ProgressDialog pd = new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage("正在查找...");
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .searchContact(content)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        pd.dismiss();

                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.d(TAG, response.code() + response.message());
                            showToast(searchView, getString(R.string.system_busy));
                            return;
                        }
                        if (commonResult.isError()) {
                            showToast(searchView, "该号码没有注册或者对方已经开启隐身模式");
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) commonResult.getData();
                        targetUser = jsonObject.toJavaObject(User.class);
                        showTargetUserInfo();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        pd.dismiss();
                        showToast(searchView, getString(R.string.system_busy));
                    }
                });

    }

    public void showTargetUserInfo() {
        searchedUserLayout.setVisibility(View.VISIBLE);
        if (targetUser.getUsername() != null) {
            nameText.setText(targetUser.getUsername());
        } else {
            nameText.setText(targetUser.getPhone());
        }
        if (targetUser != null) {
            String avatarUrl = targetUser.getAvatar();
//            Glide.with(AddContactActivity.this)
//                    .load(avatarUrl).diskCacheStrategy(DiskCacheStrategy.ALL)
//                    .placeholder(R.drawable.fx_icon_camera)
//                    .into(avatar);
            GlideLoadUtils.glideLoad(AddContactActivity.this,avatarUrl,avatar,R.drawable.fx_icon_camera);
        }
    }

    /**
     * add contact
     * 这个直接在布局中设置的 onclick
     *
     * @param view
     */

    public void addContact(final View view) {
        hideSoftKeyboard();
        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        if (Utils.isTempUser(loginUserInfo)) {
            LoginActivity.startActivity(this, "添加联系人需要先登录");
            return;
        }

        if (targetUser == null) {
            showToast_v1("请先查找要添加的联系人");
            return;
        }
        if (loginUserInfo.getuId().equals(targetUser.getuId())) {
            showToast(view, getString(R.string.not_add_myself));
            return;
        }

        if (Helper.getInstance().isNormalContact(targetUser.getuId())) {

            showToast(view, getString(R.string.This_user_is_already_your_friend));
            return;
        }

        Contact contact = new Contact();
//        final GroupFragment groupFragment = GroupFragment.newInstance();
//        groupFragment.show(getSupportFragmentManager(), "");
//        groupFragment.setInteractionListener(new GroupFragment.OnFragmentInteractionListener() {
//            @Override
//            public void onCreateOrSelectGroup(String groupName) {
//                contact.setGroupName(groupName);
//                groupFragment.dismiss();
//                final AuthorityFragment authorityFragment = AuthorityFragment.newInstance(contact);
//                authorityFragment.show(getSupportFragmentManager(), "");
//                authorityFragment.setInteractionListener(new AuthorityFragment.OnFragmentInteractionListener() {
//                    @Override
//                    public void onSetAuthorityComplete(Contact contact) {
//                        authorityFragment.dismiss();
//                        sendInviteMessage(contact);
//
//                    }
//                });
//            }
//        });
        if (cb_location.isChecked()) {
            contact.setTLocation("1");
        } else {
            contact.setTLocation("0");
        }
        sendInviteMessage(contact);

    }

    private void sendInviteMessage(Contact updateContact) {
        progressDialog = new ProgressDialog(AddContactActivity.this);
        progressDialog.setMessage(getResources().getString(R.string.Is_sending_a_request));
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        String inviteMessage = et_reason.getText().toString();
        if (TextUtils.isEmpty(inviteMessage)) {
            inviteMessage = getResources().getString(R.string.default_invite_message);
        }
        updateContact.setInviteMessage(inviteMessage);
        updateContact.settId(targetUser.getuId());

//        if (!TextUtils.isEmpty(cId)) {
//            updateContact.setcId(cId);
//        }
//        if (!TextUtils.isEmpty(tCid)) {
//            updateContact.settCid(tCid);
//        }
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .sendInviteMessage(updateContact)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressDialog.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(searchView, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            switch (result.getStatus()) {

                                case Constant.REFUSE_ADD_CONTACT:
                                    showToast(searchView, "对方已经拒绝您的添加联系人请求," + result.getData().toString() + "天后可再次添加");
                                    return;
                            }
                        }


                        if (result.getData() != null) {
                            JSONObject jsonObject = (JSONObject) result.getData();
                            Contact contact = jsonObject.toJavaObject(Contact.class);
//                            DBManager.getInstance().getDaoSession().getContactDao().insertOrReplace(contact);
//                            Helper.getInstance().refreshCache();
                            User targetUser = contact.getUser();
                            //构造一条本地消息，
                            Message message = new Message();
                            message.setId(IDUtils.genOrderItemId());
                            message.setFromId(targetUser.getuId());
                            message.setToId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                            message.setType(Constant.NOTIFY_MESSAGE);
                            message.setSubType(Constant.PUSH_MESSAGE_ACCEPT_ADD_CONTACT);
                            message.setExtraData(JSONObject.toJSONString(contact));
                            message.setVisible(Constant.MESSAGE_VISIBLE);
                            message.setCreated(new Date());
                            IMSClientBootstrap.getInstance().sendLocalMessage(message);

                        }
                        showToast(searchView, getString(R.string.send_invite_message_seccess));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressDialog.dismiss();
                        showToast(searchView, getString(R.string.system_busy));
                    }
                });
    }

    public void back(View v) {
        finish();
    }
}
